package com.itcast.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itcast.mapper.BookMapper;
import com.itcast.mapper.BorrowMapper;
import com.itcast.mapper.UserMapper;
import com.itcast.pojo.Book;
import com.itcast.pojo.BorrowedQuantity;
import com.itcast.pojo.PageBean;
import com.itcast.pojo.User;
import com.itcast.service.BookService;
import com.itcast.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BorrowMapper borrowMapper;

    /**
     * 分组查询图书
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageBean findBooks(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Book> books = bookMapper.get();
        Page<Book> p = (Page<Book>)books;
        return new PageBean(p.getTotal(),p.getResult());
    }

    /**
     * 添加图书
     * @param book
     */
    @Override
    public void add(Book book) {
        book.setCreateTime(LocalDateTime.now());
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.insert(book);
    }

    /**
     * 根据图书id查询图书（回显操作）
     * @param id
     * @return
     */
    @Override
    public Book findById(Integer id) {
        Book book = bookMapper.getById(id);
        return book;
    }

    /**
     * 修改图书
     * @param book
     */
    @Override
    public void set(Book book) {
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.update(book);
    }

    /**
     * 删除图书（仅管理员可删除）
     * @param id
     * @param token
     * @return
     */
    @Override
    @Transactional
    public Integer delete(Integer id, String token) {
        Integer userId =(Integer) JwtUtils.parseJWT(token).get("id");
        User user = userMapper.getById(userId);
        if (user.getType().equals(1)){
            return 0;
        }
        bookMapper.delete(id);
        return 1;
    }

    /**
     * 统计图书借阅情况
     * @return
     */
    @Override
    public List<BorrowedQuantity> group() {
        List<BorrowedQuantity> list = borrowMapper.group();
        return list;
    }
}
